package com.us.usws.batch.resimp;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

import org.supercsv.cellprocessor.ift.CellProcessor;
import org.supercsv.io.CsvBeanReader;
import org.supercsv.io.ICsvBeanReader;
import org.supercsv.prefs.CsvPreference;

import com.us.usws.batch.resimp.result.ResImpResult;

public abstract class ResImpAbstractWorker<T extends CSVRawResult> implements ResImpWorker<T> {

	//private static Log log = LogFactory.getFactory().getInstance(ResImpAbstractWorker.class);

	private List<T> results = new ArrayList<T>();
	private Set<ResDescFile> descFiles = new LinkedHashSet<>();

	public abstract CellProcessor[] getProcessors();

	public abstract String[] getHeaders();

	public abstract ResImpResult imp();

	public Set<ResDescFile> getDescFiles() {
		return this.descFiles;
	}

	@Override
	public ResImpWorker<T> loadCsv(ResDescFile descFile, Class<T> clz) throws IOException {
		this.descFiles.clear();
		this.results.clear();
		return loadOne(descFile, clz);
	}

	@Override
	public ResImpWorker<T> appendCsv(ResDescFile descFile, Class<T> clz) throws IOException {
		return loadOne(descFile, clz);
	}

	private ResImpWorker<T> loadOne(ResDescFile descFile, Class<T> clz) throws IOException {
		this.descFiles.add(descFile);
		ICsvBeanReader beanReader = null;
		try {

			InputStreamReader freader = new InputStreamReader(new FileInputStream(new File(descFile.getPath())), "GBK");

			beanReader = new CsvBeanReader(freader, CsvPreference.STANDARD_PREFERENCE);

			// the header elements are used to map the values to the bean (names must match)
			//final String[] header = beanReader.getHeader(true);
			final String[] header = getHeaders() == null ? beanReader.getHeader(false) : getHeaders();
			final CellProcessor[] processors = getProcessors();

			T each;
			int i = 0;
			while ((each = beanReader.read(clz, header, processors)) != null) {
				if (i != 0) {
					each.setUploadDir(descFile.getDir());
					each.setUploadFileName(descFile.getFileName());
					results.add(each);
				}
				i++;
			}

		} finally {
			if (beanReader != null) {
				beanReader.close();
			}
		}
		return this;
	}

	@Override
	public List<T> getResults() {
		return results;
	}

}
